package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/checkgroup")
public class CheckGroupController {
    @Autowired
    private CheckGroupService groupService;


    @GetMapping("/findAll")
    public Result findAll(){
        List<CheckGroup> all = groupService.findAll();
        if (all != null){
            return new Result(true, MessageConstant.QUERY_CHECKGROUP_SUCCESS,all);
        }
        return new Result(false, MessageConstant.QUERY_CHECKGROUP_FAIL);
    }

    @PostMapping("/findPage")
    public Result findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult page = groupService.findPage(queryPageBean);
        if (page != null){

            return new Result(true,MessageConstant.QUERY_CHECKGROUP_SUCCESS ,page);
        }

        return new Result(false,MessageConstant.QUERY_CHECKGROUP_FAIL);
    }

    @PostMapping("/add")
    public Result add(@RequestBody CheckGroup checkGroup,Integer[] checkItems){
        try {
            groupService.add(checkGroup,checkItems);
            return new Result(true,MessageConstant.ADD_CHECKGROUP_SUCCESS);
        }catch (Exception e){
            return new Result(false,MessageConstant.ADD_CHECKGROUP_FAIL);
        }
    }

    @GetMapping("/findById")
    public Result findById(Integer id){
        try {
            CheckGroup group = groupService.findById(id);
            if (group != null){
                return new Result(true,MessageConstant.QUERY_CHECKGROUP_SUCCESS,group);
            }else {
                return new Result(false,MessageConstant.QUERY_CHECKGROUP_SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();

            return new Result(false,MessageConstant.QUERY_CHECKGROUP_SUCCESS);
        }
    }


    @PutMapping("/edit")
    public Result edit(@RequestBody CheckGroup checkGroup,Integer[] checkItems){
        try {
            Integer row = groupService.editGroup(checkGroup, checkItems);
            if (row !=null && row == 1){
                return new Result(true,MessageConstant.EDIT_CHECKITEM_SUCCESS);
            }else {
                return new Result(false,MessageConstant.EDIT_CHECKGROUP_FAIL);
            }
        }catch (RuntimeException e){
            System.out.println(e);
            return new Result(false,MessageConstant.EDIT_CHECKGROUP_FAIL);
        }
    }





}
